const fs = require('fs')
const path = require('path')
const multer = require('multer')
const crypto = require('crypto')
const moment = require('moment')
const schedule = require('node-schedule');
const chinaTime = require('china-time');
const request = require('request');
const api = require('../api/api');
const handleMsg = require('../wechat/wechat.js');

const { findQuestions, addQuestions, deleteQuestions, editQuestions, verifyAnswer } = require('../models/questions')
const { findLuckyDraw, addLuckyDraw, deleteLuckyDraw, editLuckyDraw } = require('../models/luckyDraw')
const { findGoods, addGoods, deleteGoods, editGoods, } = require('../models/goods')
const { getUserInfo, addUser, updateUserInfo, deleteUser, getUserList } = require('../models/user')
const { addIntegral } = require('../models/integral')
const { getWxUserInfo, getAccessToken, sign, wxConfig, wechat } = require('../models/wxInterface');
const { addExchange, } = require('../models/exchange');

const { insertData, findData, findOneData, updateData, requstPromise, randomWord, getPageQuery, creatMenu, setLog } = require('../utils')

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
});

var upload = multer({
    storage: storage
});


let access_token = ''



const reAccessToken = () => {
    return new Promise((resolve, reject) => {
        getAccessToken().then(accessTokenRes => {
            console.log(accessTokenRes)
            access_token = accessTokenRes.access_token
            resolve()
            // api.get('https://api.weixin.qq.com/cgi-bin/get_current_autoreply_info', { access_token: access_token }).then(res => {
            //     console.log('————————————————————————————')
            //     console.log(JSON.stringify(res))
            //     console.log('————————————————————————————')
            // }) //发送模板消息的数据
        })
    }).catch(error => console.log(error))
}


const scheduleCronstyle = () => {
    // 
    console.log('初始化定时任务')
    schedule.scheduleJob('0 0 0 * * *', () => {
        console.log('scheduleCronstyle:' + moment().format('YYYY-MM-DD HH:mm:ss'));
        setUserIntegral()
    });
}


const setUserIntegral = async (res) => {
    const userList = await getUserList()
    userList.map(item => {
        const { openid } = item
        updateUserInfo({
            openid,
            answer: 1,
            isShare: false,
            shareNum: 10,
            luckyDrawNum: 1,
            isSign: false
        }).then(result => {
            console.log(openid + '添加成功')
        }).catch(error => {
            console.log(openid + '添加失败')
        })
    })
}


const pushTemplate = async () => {
    const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`; //发送模板消息的接口
    const userList = await getUserList()
    userList.map(item => {
        const { openid } = item
        api.post(url, { //发送模板消息的数据
            touser: openid,
            template_id: '7N4FHTrnKVjqeRKAiJVt-ca5QUrNJsfZixZ6EUSccCQ',
            url: 'http://www.camluni.com/questions/',
        }).then(templateRes => {
            console.log(templateRes, '推送信息')
        })
    })
}


const scheduleCronstylePushTemplate = async () => {
    // 每天早上9点执行
    console.log('初始化定时模板推送')
    console.log(moment().format('YYYY-MM-DD HH:mm:ss'))
    schedule.scheduleJob('0 0 09 * * *', async () => {
        console.log(1)
        console.log('scheduleCronstylePushTemplate:' + moment().format('YYYY-MM-DD HH:mm:ss'));

        let projectInfo = await findOneData('camluniProject', { id: '1' })
        let isBetween = moment().isBetween(projectInfo.timeStart, projectInfo.timeEnd, 'days') || moment().isSame(projectInfo.timeStart, 'days') || moment().isSame(projectInfo.timeEnd, 'days')
        if (isBetween) {
            // pushTemplate()
        }
    });
}

const scheduleCronstyleReAccessToken = () => {
    // 每两小时执行一次
    console.log('初始化定时刷新 AccessToken')
    setInterval(() => {
        console.log('scheduleCronstyleReAccessToken:' + moment().format('YYYY-MM-DD HH:mm:ss'));
        reAccessToken()
    }, 7200 * 1000)
}

const setDefaultConfig = async () => {
    await reAccessToken();
    scheduleCronstyle();
    scheduleCronstylePushTemplate()
    scheduleCronstyleReAccessToken()
    creatMenu(api, access_token)
}

setDefaultConfig()

module.exports = function (app) {

    app.all('*', function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        res.header("Content-Type", "application/json;charset=utf-8");
        if (req.method == "OPTIONS") {
            //  antd中 需要去掉 credentials: 'include'
            res.sendStatus(200); /* 让options请求快速返回*/
        } else {
            next();
        }
    });

    // app.get('/questions', async  (req, res) =>{
    //     //判断是否是第一页，并把请求的页数转换成 number 类型
    //     //查询并返回第 page 页的 10 篇文章
    //     console.log("开始查询数据库")
    //     // setUserIntegral(res)
    //     // res.render('/questions/index');
    //     res.sendFile(path.join(__dirname, "../public/questions/index.html"))
    // });



    app.post('/project', async (req, res) => {
        //判断是否是第一页，并把请求的页数转换成 number 类型
        //查询并返回第 page 页的 10 篇文章
        console.log("开始查询数据库")
        // setUserIntegral(res)
        // findOneData()
        const { id, name, time, ranking, number, info } = req.body
        let projectData = await findOneData('camluniProject', { id })
        // let updateProjectData
        console.log(projectData, 852963)
        console.log(req.body, 10000000)
        if (!projectData) {
            console.log('插入数据')
            projectData = await insertData('camluniProject', {
                id,
                name,
                timeStart: time[0],
                timeEnd: time[1],
                rankingIntegral: ranking,
                number: number,
                info
            })
        } else {
            console.log({
                name,
                timeStart: time[0],
                timeEnd: time[1],
                rankingIntegral: ranking,
            }, '更新数据')
            projectData = await updateData('camluniProject', { id }, {
                name,
                timeStart: time[0],
                timeEnd: time[1],
                rankingIntegral: ranking,
                number: number,
                info
            })
        }
        res.json({
            success: true,
            message: '添加成功',
            data: projectData
        });
    });

    app.get('/projectInfo', async (req, res) => {
        console.log(req.query)
        let projectData = await findOneData('camluniProject', { id: req.query.id })
        console.log(projectData, '详情')
        if (projectData) {
            res.json({
                success: true,
                message: '请求成功',
                data: projectData
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                data: projectData
            });
        }
    });
    app.post('/updateUserInfo', async (req, res) => {
        console.log(req.body)
        let user = updateUserInfo(req.body)
        console.log(user, 'sjsjsjsjsj')
        if (user) {
            res.json({
                success: true,
                message: '请求成功',
                data: user
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                data: user
            });
        }
    });

    app.get('/wx', async (req, res) => {
        res.header("Access-Control-Allow-Origin", "*");
        console.log(res.req.query, 'wx')
        const echostr = res.req.query.echostr || 'text'
        console.log(echostr)
        res.send(echostr)
        // res.json({
        //     echostr: 'text'
        // })
    });

    app.post('/wx', async (req, res) => {
        res.header("Access-Control-Allow-Origin", "*");
        // console.log(req.query, 'query')
        // console.log(req.body, 'body')
        // const echostr = res.req.query.echostr
        // console.log(echostr)
        // res.send(echostr)
        handleMsg(req, res);
        // res.json(res.req.query.echostr)
    });

    app.post('/wxinterface', async (req, res) => {
        let myCode = req.body.code;
        let inviter = req.body.inviter;
        let source = req.body.source;
        let result = await getWxUserInfo(myCode)

        // setLog('查看是否是分享进来的', req.body)
        // setLog('服务器获取到微信用户信息', result)
        setLog('查找是否有用户信息存在', 0)

        if (result && result.openid) {

            setLog('微信用户信息存在', 1)

            let userInfo = await getUserInfo({ openid: result.openid })

            setLog('查找是否有用户信息存在结果', userInfo && userInfo.ops ? userInfo.ops : null)

            if (userInfo && userInfo.openid) {

                // setLog('存在该用户，刷新数据', userInfo)
                setLog('刷新数据', userInfo.nickname)

                let updateUser = await updateUserInfo(result)

                // setLog('刷新结果', updateUser && updateUser.ops ? updateUser.ops : updateUser)
                setLog('请求最新的数据', 0)

                let userData = await getUserInfo({ openid: result.openid })

                setLog('最新用户信息', userData && userData.ops ? userData.ops : userData)

                if (userData) {
                    res.json({
                        success: true,
                        message: '更新成功',
                        data: userData
                    });
                }
            } else {
                setLog('用户不存在', inviter)
                setLog('添加用户', inviter)

                let addUserData = await addUser({ ...result, inviter: inviter && inviter != 'undefined' ? inviter : result.openid, source })

                setLog('新添加用户添加结果', addUserData && addUserData.ops ? addUserData.ops : addUserData)
                if (addUserData) {
                    setLog('判断是不是分享进来的', inviter)
                    if (inviter && inviter != 'undefined') {
                        setLog('通过邀请链接进入', inviter)
                        // TUDO 邀请新好友点击进来，给用户加分，但是不能超过50分
                        setLog('给邀请好友的用户加积分', inviter)
                        let user = await getUserInfo({ openid: inviter })
                        if (user) {
                            let integralList = user.integralList
                            let shareNum = user.shareNum
                            if (shareNum <= 0) {
                                setLog('今天用户已经超过50分了', inviter)
                                console.log(inviter, '今天用户已经超过50分了')
                            } else {
                                let addIntegralNum = 5
                                let integral = user.integral
                                integral = integral + addIntegralNum
                                shareNum = shareNum - 1
                                integralList.push({
                                    type: 4,
                                    integral: addIntegralNum,
                                    date: moment().format('YYYY-MM-DD HH:mm:ss')
                                })
                                await updateUserInfo({
                                    openid: inviter,
                                    integral: integral,
                                    shareNum: shareNum,
                                    integralList
                                })
                            }
                        }
                    }

                    let userInfoData = await getUserInfo({ openid: result.openid })
                    if (userInfoData) {
                        res.json({
                            success: true,
                            message: '更新成功',
                            data: userInfoData
                        });
                    } else {
                        res.json({
                            success: false,
                            message: '更新失败',
                            error: error
                        });
                    }
                } else {
                    res.json({
                        success: false,
                        message: '添加失败',
                        error: error
                    });
                }
            }
        }
    })

    app.get('/creatMenu', async (req, res) => {
        api.post(`https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${access_token}`, {
            "button": [{
                "name": "火热上新",
                "sub_button": [{
                    "type": "view",
                    "name": "预约试听课",
                    "url": "http://cn.mikecrm.com/SKJ74EH",
                    "sub_button": []
                }, {
                    "type": "view",
                    "name": "科学实验室",
                    "url": "http://mp.weixin.qq.com/s?__biz=MzI0NDI4NDYwNA==&mid=2247485802&idx=1&sn=5023b5f13900b4b03fcfe375122e3efb&chksm=e96164b9de16edaf15cab58327f19b6baa4706a8949d78fe1c0b5c67c0ec0024e404033375e3&scene=18#wechat_redirect",
                    "sub_button": []
                }]
            }, {
                "name": "关于我们",
                "sub_button": [{
                    "type": "view",
                    "name": "官方网站",
                    "url": "http://www.camluni.com/",
                    "sub_button": []
                }, {
                    "type": "view",
                    "name": "课程介绍",
                    "url": "https://mp.weixin.qq.com/s/-brMTGenVYN3GXYPiSgTig",
                    "sub_button": []
                }, {
                    "type": "view",
                    "name": "文章目录",
                    "url": "http://mp.weixin.qq.com/mp/homepage?__biz=MzI0NDI4NDYwNA==&hid=1&sn=170e510775f2f9eb52564fc1a71323ee&scene=18#wechat_redirect",
                    "sub_button": []
                }, {
                    "type": "view",
                    "name": "联系我们",
                    "url": "https://mp.weixin.qq.com/s/-6IXFaaowOq2DJ1ngrOn4A",
                    "sub_button": []
                }, {
                    "type": "view",
                    "name": "卡墨微店",
                    "url": "https://weidian.com/?userid=1343867711&spider_token=5e93&spider=seller.new_item_detail.shop_info_wrap.2",
                    "sub_button": []
                }]
            }, {
                "name": "会员中心",
                "sub_button": [{
                    "type": "view",
                    "name": "我的主页",
                    "url": "https://open.xgjssx.com/Jump/Page?name=main&terminal=1&app=wxbc2631875fcdbfb3",
                    "sub_button": []
                }, {
                    "type": "view",
                    "name": "会员福利",
                    "url": "https://mp.weixin.qq.com/s?__biz=MzI0NDI4NDYwNA==&mid=2247485401&idx=2&sn=5a0a39a0e3818c68007100ed18948d58&chksm=e9616a0ade16e31c02b44690b2f7bc198d1bcc71eab95fd637e050f1f3879f60fdeb67607eae&scene=18#rd",
                    "sub_button": []
                }, {
                    "type": "view",
                    "name": "切换用户",
                    "url": "https://open.xgjssx.com/Login/Change?terminal=1&app=wxbc2631875fcdbfb3",
                    "sub_button": []
                }, {
                    "type": "view",
                    "name": "绑定新用户",
                    "url": "https://open.xgjssx.com/Login/Index?terminal=1&app=wxbc2631875fcdbfb3",
                    "sub_button": []
                }]
            }]
        }).then(createRes => {
            console.log(createRes)
            res.json({
                data: createRes
            })
        })
    })


    app.get('/wxConfig', async (req, res) => {
        sign(req.query.url, access_token, function (signatureMap) {
            res.json({
                success: true,
                message: '请求成功',
                data: signatureMap
            });
        });

    })

    app.post('/share', async (req, res) => {
        const { openid } = req.body
        let user = await getUserInfo({ openid })
        let integralList = user.integralList
        let integral = user.integral
        let answer = user.answer
        if (user.isShare) {
            res.json({
                success: false,
                message: '分享成功，邀请好友获得更多积分哦~',
            });
            return
        }
        // integral = integral + 5
        // integralList.push({
        //     type: 3,
        //     integral: 5,
        //     date: moment().format('YYYY-MM-DD HH:mm:ss')
        // })
        let updateUser = await updateUserInfo({
            openid,
            answer: answer + 1,
            isShare: true,
            integral: integral,
            integralList
        })
        if (updateUser) {
            res.json({
                success: true,
                message: '恭喜您获得一次答题机会~',
            });
        } else {
            res.json({
                success: false,
                message: '更新失败',
            });
        }
    })


    app.post('/addUserFriend', async (req, res) => {
        const { openid, inviter } = req.body
        let updateUser = await updateUserInfo({
            openid,
            inviter,
        })
        if (updateUser) {
            res.json({
                success: true,
                message: '分享成功，积分+3',
            });
        } else {
            res.json({
                success: false,
                message: '更新失败',
            });
        }
    })



    app.post('/upload', async (req, res) => {
        if (!req.body.img) {
            res.json({
                success: false,
                message: '请上传图片',
            });
            return
        }
        //过滤图片url
        let base64 = req.body.img.replace(/^data:image\/\w+;base64,/, "")
        //把图片转换成buffer对象
        let dataBuffer = new Buffer(base64, 'base64')
        //保存图片的地址是
        let path = '/images/' + new Date().getTime() + '.jpg'
        //保存图片
        fs.writeFile(`public${path}`, dataBuffer, (err) => {
            if (err) {
                console.log(err)
            } else {
                res.json({
                    success: true,
                    message: '添加成功',
                    data: path
                });
            }
        })
    });


    app.post('/getUserInfo', async (req, res) => {
        if (!req.body.openid) {
            res.json({
                success: false,
                message: '未传递openid',
            });
            return
        }
        let result = await getUserInfo(req.body)
        if (result) {
            res.json({
                success: true,
                message: '更新成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '更新失败',
                error: result
            });
        }
    });


    app.get('/deleteUser', async (req, res) => {
        console.log(req.query)
        if (!req.query.openid) {
            res.json({
                success: false,
                message: '未传递openid',
            });
            return
        }
        let result = await deleteUser(req.query.openid)
        if (result) {
            res.json({
                success: true,
                message: '更新成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '更新失败',
                error: result
            });
        }
    })



    app.get('/getQuestions', async (req, res) => {
        if (JSON.stringify(req.query) != "{}") {
            let option = getPageQuery(req.query)
            const { pageIndex, pageSize } = req.query
            // title 支持模糊查询
            if (option.data.title) {
                option.data.title = { $regex: option.data.title, $options: 'i' }
            }

            let allQuestions = await findData('camluniQuestions')
            let result = await findData('camluniQuestions', option.data, { 'creatTime': -1 }, option.skip, option.limit)

            if (result) {
                res.json({
                    success: true,
                    message: '请求成功',
                    data: {
                        pageIndex,
                        pageSize,
                        total: allQuestions.length,
                        data: result
                    }
                });
            } else {
                res.json({
                    success: false,
                    message: '请求失败',
                    error: result
                });
            }
        } else {
            let result = await findData('camluniQuestions')
            console.log(result, 2202020200202)
            if (result) {
                res.json({
                    success: true,
                    message: '请求成功',
                    data: {
                        pageIndex: 1,
                        pageSize: result.length,
                        total: result.length,
                        data: result
                    }
                });
            } else {
                res.json({
                    success: false,
                    message: '请求失败',
                    error: result
                });
            }
        }

    });


    app.get('/getQuestionsNumber', async (req, res) => {
        let allQuestions = await findData('camluniQuestions')
        let questions = await findData('camluniQuestions', { collection: '1' })

        if (allQuestions && questions) {
            res.json({
                success: true,
                message: '请求成功',
                data: {
                    total: allQuestions.length,
                    questions: questions.length,
                }
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
            });
        }
    });

    app.get('/dailyQuestions', async (req, res) => {

        const { collection } = req.query
        // 通过获取起止时间，用来补充少的题目
        let projectInfo = await findOneData('camluniProject', { id: '1' })
        // 判断当前是否设置了开始结束时间
        if (projectInfo.timeStart && projectInfo.timeEnd) {
            // 今天
            let day = moment().format('YYYY-MM-DD')
            // 当前是第几天
            let activeDay = moment(day).diff(projectInfo.timeStart, 'days')
            console.log(activeDay, day, projectInfo.timeStart)
            projectInfo.number = parseInt(projectInfo.number)
            // 1  0*5 + 0 * 5   0
            // 1  0*5 + 5   5
            // 1  1*5 + 1 * 5   10
            // 1  1*5 + 1 * 5 + 5   15
            // 1  2*5 + 2 * 5   20
            // 1  2*5 + 2 * 5 + 5   25
            let page = 0
            if (collection == 1) {
                page = projectInfo.number * activeDay + projectInfo.number * activeDay
            } else {
                page = projectInfo.number * activeDay + projectInfo.number * activeDay + projectInfo.number
            }

            if (!projectInfo.number) {
                projectInfo.number = 5
            }

            // let result = await findData('camluniQuestions', { collection: '1' }, { 'index': 1 })
            let result = await findData('camluniQuestions', { collection: '1' }, { 'index': 1 }, page, parseInt(projectInfo.number))
            if (result) {
                res.json({
                    success: true,
                    message: '请求成功',
                    data: result
                });
            } else {
                res.json({
                    success: false,
                    message: '请求失败',
                    error: result
                });
            }
            return
        }
        res.json({
            success: false,
            message: '请求失败',
            error: result
        });
    });

    app.post('/addQuestions', async (req, res) => {
        let result = await addQuestions(req.body)
        if (result) {
            res.json({
                success: true,
                message: '添加成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '添加失败',
                error: result
            });
        }
    });

    app.get('/deleteQuestions', async (req, res) => {
        result = await deleteQuestions(req.query.id)
        if (result) {
            res.json({
                success: true,
                message: '删除成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '删除失败',
                error: result
            });
        }
    });

    app.post('/editQuestions', async (req, res) => {
        result = await editQuestions(req.body)
        if (result) {
            res.json({
                success: true,
                message: '修改成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '修改失败',
                error: result
            });
        }
    });

    app.post('/editQuestionsList', async (req, res) => {

        let questionsList = await findQuestions()

        // 重置所有数据的状态
        questionsList.map(async item => {
            await editQuestions({ id: item.id, collection: null, index: null })
        })
        console.log(questionsList.length, 790)
        // 题库少于要展示的题目
        if (questionsList.length >= req.body.list.length) {
            // 通过获取起止时间，用来补充少的题目
            let projectInfo = await findOneData('camluniProject', { id: '1' })
            let day = null
            // 判断当前是否设置了开始结束时间
            if (projectInfo.timeStart && projectInfo.timeEnd) {
                day = moment(projectInfo.timeEnd).diff(projectInfo.timeStart, 'days') + 1
            } else {
                res.json({
                    success: false,
                    message: '请设置开始结束时间',
                });
                return
            }
            // 判断选择的题目是否够本次活动的数量，不够的补充
            if (day && day * 2 * projectInfo.number > req.body.list.length) {
                let questionsListKey = questionsList.map(item => item.id)
                for (let i = 0; i < questionsListKey.length; i++) {
                    for (let y = 0; y < req.body.list.length; y++) {
                        if (questionsListKey[i] == req.body.list[y]) {
                            questionsListKey.splice(i, 1)
                            i--
                        }
                    }
                }
                for (let i = 0; i < questionsListKey.length; i++) {
                    let item = questionsListKey[i]
                    console.log(item)
                    if (day * 2 * projectInfo.number > req.body.list.length) {
                        req.body.list.push(item)
                    } else {
                        break
                    }
                }
            }
        } else {
            res.json({
                success: false,
                message: '题目数量不足，请补充',
            });
            return
        }

        // 将指定列表放入答题列表
        req.body.list.map(async (item, index) => {
            await editQuestions({ id: item, collection: '1', index: index + 1 })
        })

        res.json({
            success: true,
            message: '修改成功',
        });

    });

    app.post('/startQuestions', async (req, res) => {
        if (!req.body.openid) {
            res.json({
                success: false,
                message: '未传递openid',
            });
            return
        }
        const user = await getUserInfo({ openid: req.body.openid })
        if (user && user.openid) {
            let openid = user.openid
            let prevLoginDate = user.prevLoginDate
            let integral = user.integral
            let answer = user.answer
            let continuous = user.continuous
            let integralList = user.integralList
            let isSign = user.isSign

            // 获取昨天的时间
            let today = moment(moment().format('YYYY-MM-DD HH:mm:ss')).subtract(1, 'days').format('YYYY-MM-DD hh:mm:ss')
            // 上一次登陆是不是昨天
            let isToday = moment(today).isSame(prevLoginDate, 'days')
            // 默认送积分0
            let addIntegral = integral
            console.log(today)
            console.log(prevLoginDate)
            console.log(isToday)
            if (answer <= 0) {
                res.json({
                    success: false,
                    message: '没有答题次数了',
                });
                return
            }
            // 判断是否签到了，如果签到了，扣除次数，
            if (isSign) {
                answer = answer - 1
            } else {
                addIntegral = 0
                if (isToday) {
                    // 是昨天连续登陆+1
                    continuous = continuous + 1
                } else {
                    // 不是昨天，当前签到1
                    continuous = 1
                }
                if (continuous == 2) {
                    addIntegral = 5
                }
                if (continuous == 3) {
                    addIntegral = 7
                }
                if (continuous >= 4) {
                    addIntegral = 10
                }
                integral = addIntegral + integral
                answer = answer - 1
                if (addIntegral > 0) {
                    integralList.push({
                        type: 2,
                        integral: addIntegral,
                        date: moment().format('YYYY-MM-DD HH:mm:ss')
                    })
                }

                setLog('开始答题', {
                    openid,
                    prevLoginDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                    continuous,
                    integral,
                    answer,
                    integralList,
                    isSign: true,
                })
            }


            let result = await updateUserInfo({
                openid,
                prevLoginDate: moment().format('YYYY-MM-DD HH:mm:ss'),
                continuous,
                integral,
                answer,
                integralList,
                isSign: true,
            })
            if (result) {
                // isSign true 已经签到了
                // isSign fase 签到成功
                res.json({
                    success: isSign ? false : true,
                    message: isSign ? '已经签到了' : '签到成功',
                    data: {
                        day: continuous,
                        integral: addIntegral
                    }
                });
            } else {
                res.json({
                    success: false,
                    message: '请求失败',
                    error: error
                });
            }
        }
    });

    // 判断上次答题时间，如果是昨天，那就加1，并且刷新上次登录时间
    app.post('/verifyAnswer', async (req, res) => {
        if (!req.body.openid) {
            res.json({
                success: false,
                message: '未传递openid',
            });
            return
        }
        const user = await getUserInfo({ openid: req.body.openid })
        let openid = user.openid
        let integral = user.integral
        let integralList = user.integralList
        let result = await verifyAnswer(req.body)
        if (result) {
            integral += 10
            integralList.push({
                type: 1,
                integral: 10,
                date: moment().format('YYYY-MM-DD HH:mm:ss')
            })
            let updateUser = updateUserInfo({
                openid,
                integral,
                integralList
            })
            if (updateUser) {
                res.json({
                    success: true,
                    message: '请求成功',
                    data: updateUser
                });
            } else {
                res.json({
                    success: false,
                    message: '请求失败',
                    error: updateUser
                });
            }
        } else {
            res.json({
                success: false,
                message: '请求失败',
                error: result
            });
        }

    });


    app.get('/getLuckyDraw', async (req, res) => {
        let result = await findLuckyDraw(req.query)
        if (result) {
            res.json({
                success: true,
                message: '请求成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                error: result
            });
        }
    });

    app.post('/addLuckyDraw', async (req, res) => {
        let result = await addLuckyDraw(req.body)
        if (result) {
            res.json({
                success: true,
                message: '添加成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '添加失败',
                error: result
            });
        }
    });

    app.get('/deleteLuckyDraw', async (req, res) => {
        let result = await deleteLuckyDraw(req.query.id)
        if (result) {
            res.json({
                success: true,
                message: '删除成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '删除失败',
                error: result
            });
        }
    });

    app.post('/editLuckyDraw', async (req, res) => {
        let result = await editLuckyDraw(req.body)
        if (result) {
            res.json({
                success: true,
                message: '添加成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '添加失败',
                error: result
            });
        }
    });

    app.post('/setLuckyDraw', async (req, res) => {
        try {
            for (let attr in req.body) {
                await editLuckyDraw({ id: attr, award: '1', probability: req.body[attr] })
            }
            res.json({
                success: true,
                message: '设置成功',
            });
        } catch (error) {
            res.json({
                success: false,
                message: '设置失败',
                error: error
            });
        }
    });


    app.get('/getGoods', async (req, res) => {
        let result = await findGoods(req.query)
        if (result) {
            res.json({
                success: true,
                message: '请求成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                error: result
            });
        }
    });
    app.get('/getGoodsInfo', async (req, res) => {
        let result = await findGoods(req.query)
        if (result) {
            if (result.length > 0) {
                result = result[0]
            }
            res.json({
                success: true,
                message: '请求成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                error: result
            });
        }
    });

    app.post('/addGoods', async (req, res) => {
        let result = await addGoods(req.body)
        if (result) {
            res.json({
                success: true,
                message: '添加成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '添加失败',
                error: result
            });
        }
    });

    app.get('/deleteGoods', async (req, res) => {
        let result = await deleteGoods(req.query.id)
        if (result) {
            res.json({
                success: true,
                message: '删除成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '删除失败',
                error: result
            });
        }
    });

    app.post('/editGoods', async (req, res) => {
        let result = await editGoods(req.body)
        if (result) {
            res.json({
                success: true,
                message: '添加成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '添加失败',
                error: result
            });
        }
    });

    app.post('/exchangeGoods', async (req, res) => {
        let query = req.body
        let goods = await findGoods({ id: query.goodsId });
        let user = await getUserInfo({ openid: query.openid });
        console.log('--------------')
        console.log(query)
        console.log(goods)
        console.log(user)
        console.log('--------------')
        if (goods instanceof Array && goods.length > 0) {
            goods = goods[0]
            if (goods.price > user.integral) {
                res.json({
                    success: false,
                    message: '积分不足',
                });
            } else {
                let integral = user.integral
                let updateUser = updateUserInfo({
                    openid: query.openid,
                    integral: integral - goods.price
                })
                if (updateUser) {
                    let exchange = await addExchange({
                        goodsId: goods.id, // 商品id
                        goodsName: goods.title, // 商品名称
                        goodsPic: goods.describePic, // 商品图片
                        goodsIntegral: goods.price, // 兑换所用积分
                        name: query.name, // 兑换人姓名
                        address: query.address, // 兑换人地址
                        phone: query.phone, // 兑换人地址
                    })
                    if (exchange) {
                        res.json({
                            success: true,
                            message: '兑换成功',
                        });
                    } else {
                        res.json({
                            success: true,
                            message: '兑换失败',
                        });
                    }
                } else {
                    res.json({
                        success: true,
                        message: '兑换失败',
                    });
                }
            }
        } else {
            res.json({
                success: false,
                message: '不存在该商品',
            });
        }
    });

    app.get('/getAllList', async (req, res) => {
        const result = await getUserList({}, { 'integral': -1 })
        if (result) {
            res.json({
                success: true,
                message: '请求成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                data: result
            });
        }
    });

    app.get('/getFriendList', async (req, res) => {
        const result = await getUserList({ 'inviter': req.query.openid }, { 'integral': -1 })
        if (result) {
            res.json({
                success: true,
                message: '请求成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                data: result
            });
        }
    });

    app.get('/getGoodsExchangeList', async (req, res) => {
        let result = await findData('camluniExchange')
        if (result) {
            res.json({
                success: true,
                message: '请求成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                data: result
            });
        }
    });

    app.get('/getLuckyDrawRecord', async (req, res) => {
        let result = await findData('camluniLuckyDrawRecord', req.query)
        if (result) {
            res.json({
                success: true,
                message: '请求成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                data: result
            });
        }
    });

    app.get('/getLuckyDrawRecord', async (req, res) => {
        console.log(req.query)
        let result = await findData('camluniLuckyDrawRecord', req.query)
        if (result) {
            res.json({
                success: true,
                message: '请求成功',
                data: result
            });
        } else {
            res.json({
                success: false,
                message: '请求失败',
                data: result
            });
        }
    });


    app.post('/luckyDraw', async (req, res) => {
        console.log(req.body)
        const { openid } = req.body
        if (!openid) {
            res.json({
                success: false,
                message: '未传递用户id',
            });
            return
        }
        const user = await getUserInfo({ openid })
        let luckyDrawNum = user.luckyDrawNum
        if (luckyDrawNum <= 0) {
            res.json({
                success: false,
                message: '今天没有抽奖的次数了',
                // data: data
            });
            return
        }
        luckyDrawNum = luckyDrawNum - 1
        console.log(luckyDrawNum)
        await updateUserInfo({ openid, luckyDrawNum })

        let list = await findLuckyDraw({ award: '1' })

        let ary = []

        list.forEach(item => {
            for (let i = 0; i < item.probability; i++) {
                ary.push(item)
            }
        })

        random = Math.floor(Math.random() * 100 + 1);
        console.log(random)
        let data = []
        if (ary[random]) {
            data = ary[random]
            console.log(data)
            let integralList = user.integralList
            let integral = user.integral
            let luckyDrawIntegral = parseFloat(ary[random].title)
            if (!luckyDrawIntegral) {
                luckyDrawIntegral = 0
            }
            integral = integral + luckyDrawIntegral
            console.log(integral)
            integralList.push({
                type: 5,
                integral: parseFloat(ary[random].title),
                date: moment().format('YYYY-MM-DD HH:mm:ss')
            })
            await updateUserInfo({
                openid: openid,
                integral: integral,
                integralList
            })
            res.json({
                success: true,
                message: '请求成功',
                data: [ary[random]]
            });
        } else {
            data = { id: 0, title: '未中奖' }
            res.json({
                success: true,
                message: '未中奖',
                data: [data]
            });
        }

        await insertData('camluniLuckyDrawRecord', {
            id: randomWord(false, 43),
            name: user.nickname,
            headimgurl: user.headimgurl,
            openid: user.openid,
            luckyDraw: data.title
        })

    });


    // app.get('/wechatTemplate', async (req, res) => {
    //     const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`; //发送模板消息的接口
    //     const userList = await getUserList()
    //     userList.map(item => {
    //         const { openid } = item
    //         api.post(url, { //发送模板消息的数据
    //             touser: openid,
    //             template_id: '7N4FHTrnKVjqeRKAiJVt-ca5QUrNJsfZixZ6EUSccCQ',
    //             url: 'http://wx.camluni.com/questions/',
    //             data: {
    //                 // first: {
    //                 //     value: '身份信息',
    //                 //     color: "#173177"
    //                 // },
    //                 // keyword1: {
    //                 //     value: '张三',
    //                 //     color: '#1d1d1d'
    //                 // },
    //                 // keyword2: {
    //                 //     value: '男',
    //                 //     color: '#1d1d1d'
    //                 // },
    //                 // keyword3: {
    //                 //     value: '45',
    //                 //     color: '#1d1d1d'
    //                 // },
    //                 // remark: {
    //                 //     value: '已登记！',
    //                 //     color: '#173177'
    //                 // }
    //             }
    //         }).then(templateRes => {
    //             console.log(templateRes, '推送信息')
    //             res.json({
    //                 success: true,
    //                 message: '推送 openid',
    //                 data: templateRes
    //             });
    //         })
    //     })
    // });

};
